<template>
  <div class="page">
    <div class="main">
      <el-card class="box-card" style="height:800px">
        <div slot="header" class="clearfix">
          <span>
            <navigation />
          </span>
          <el-button
            type="primary"
            v-if="userinfoId == 1 ? true : false"
            class="place"
            @click="addTask()"
            >新增任务</el-button
          >
        </div>
        <div class="list" id="indicatorsList">
          <el-scrollbar class="page-component__scroll" style="height:100%">
            <div style="height:700px;">
              <el-table
                :header-cell-style="{ background: '#f5f5f5' }"
                :data="tableData"
                style="width: 100%;margin-bottom: 20px;"
                row-key="id"
                border
                height="680px"
                :default-expand-all="false"
                :tree-props="{
                  children: 'children',
                  hasChildren: 'hasChildren'
                }"
              >
                <el-table-column
                  label="序号"
                  width="100"
                  prop="index"
                  align="center"
                >
                </el-table-column>
                <el-table-column prop="name" label="重点工作名称">
                </el-table-column>
                <el-table-column
                  prop="number"
                  label="全年目标任务量"
                  width="180"
                >
                </el-table-column>
                <el-table-column prop="year" label="年度" width="100">
                </el-table-column>
                <el-table-column label="审核状态" width="140">
                  <template
                    slot-scope="scope"
                    v-if="!scope.row.children || scope.row.children.length == 0"
                    >{{ degreeStatus(scope.row.checkStatus) }}</template
                  >
                </el-table-column>
                <el-table-column label="操作时间" width="140">
                  <template
                    slot-scope="scope"
                    v-if="scope.row.checkStatus == 1"
                    >{{ timestampToTimes(scope.row.updateTime) }}</template
                  >
                </el-table-column>
                <el-table-column prop="applicatName" label="申请人" width="100">
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                      @click="addMission(scope.row)"
                      type="text"
                      :disabled="
                        scope.row.checkStatus == 2 || scope.row.checkStatus == 1
                          ? true
                          : false
                      "
                      v-if="
                        !scope.row.children || scope.row.children.length == 0
                      "
                      >新增目标任务</el-button
                    >
                    <el-button
                      @click="routerPath(scope.row)"
                      type="text"
                      v-if="
                        !scope.row.children || scope.row.children.length == 0
                      "
                      >分解</el-button
                    >
                    <el-button
                      type="text"
                      v-if="userinfoId == 1 ? true : false"
                      :disabled="scope.row.checkStatus == 2 ? true : false"
                      @click="updata(scope.row)"
                      style="margin-bottom: 4px;"
                      >修改</el-button
                    >
                    <!-- checkStatus -->
                    <el-button
                      type="text"
                      :disabled="
                        scope.row.checkStatus == 0 ||
                        scope.row.checkStatus == -1
                          ? false
                          : true
                      "
                      v-if="showDisplay(scope.row)"
                      @click="audit(scope.row)"
                      style="margin-bottom: 4px;"
                      >上报</el-button
                    >

                    <el-button
                      @click="handleDelete(scope.row)"
                      type="text"
                      v-if="
                        !scope.row.children || scope.row.children.length == 0
                      "
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-scrollbar>
        </div>
      </el-card>
    </div>

    <!-- 新增任务 -->
    <el-dialog :title="isFlag?'新增任务':'修改任务'" center :visible.sync="dialogFormVisible">
      <div class="radio">
        <el-switch
          v-model="value1"
          :disabled="!isFlag"
          active-text="增加子任务"
          inactive-text="不增加子任务"
        >
        </el-switch>
      </div>
      <el-form :model="form">
        <el-form-item
          label="重点任务名称"
          :label-width="formLabelWidth"
          v-if="value1"
        >
          <el-select
            v-model="form.parentId"
            clearable
            filterable
            size="medium"
            style="width:100%"
            placeholder="请选择重点任务名称"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="(item, index) in tableDataboy"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          :label="value1 ? '子任务名称' : '重点任务名称'"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.name"
            size="medium"
            style="width:100%"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item
          :label="value1 ? '子任务简称' : '重点任务简称'"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.title"
            size="medium"
            style="width:100%"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="领导小组" :label-width="formLabelWidth">
          <el-cascader
            v-model="form.departmentId"
            :options="sectionOptions"
            :props="departmentProp"
            @change="changeFamily1"
            style="width:100%"
            ref="departmenref"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="年份" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.year"
            type="year"
            size="small"
            placeholder="选择年"
            style="width:100%"
            value-format="yyyy"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addnewTask()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      pageNum: 1, //第几页
      pageSize: 10, //每页几条
      total: 0, //条数
      options: [],
      isFlag:true,
      value: "",
      input: "",
      tableData: [],
      multipleSelection: [],
      sectionOptions: [],
      departmentProp: {
        label: "name",
        value: "id",
        children: "departments"
      },
      currentPage1: 5,
      currentPage2: 5,
      currentPage3: 5,
      currentPage4: 4,
      dialogFormVisible: false,
      formLabelWidth: "120px",
      value1: false,
      form: {
        id: "",
        name: "",
        parentId: "",
        departmentId: "",
        year: "",
        title: ""
      },
      branchList: [], //获取部门列表
      spanData: [],
      pos: "",
      tableDataboy: [],
      up: false,
      userinfoId: ""
    };
  },
  mounted() {
    this.userinfoId = localStorage.getItem("groupId");
    this.getbranchList();
    this.getListByPage();
    this.getdepartmentTypeList();
  },
  methods: {
    getdepartmentTypeList() {
      this.$axios
        .post("dept/getDepartmentTypeList")
        .then(res => {
          if (res.code == 200) {
            this.sectionOptions = [];
            res.data.forEach((item, index) => {
              if (item.id == 1 || item.id == 5) {
                this.sectionOptions.push(item);
              }
            });
          }
        })
        .catch(err => {});
    },
    changeFamily1(val) {
      console.log(this.value);
    },
    showDisplay(val) {
      if (val.isDisplay == true) {
        if (!val.children || val.children.length == 0) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    // 时间转换
    timestampToTimes(timestamp) {
      var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear();
      var M =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1;
      var D = date.getDate() + " ";
      var h = date.getHours() + ":";
      var m = date.getMinutes() + ":";
      var s = date.getSeconds();
      // return Y + M + D;
      let _time = `${Y}年${M}月${D}日`;
      return _time;
    },
    // 审核状态
    degreeStatus(val) {
      let _text = "";
      switch (val) {
        case 0:
          _text = "未提交";
          break;
        case 1:
          _text = "审核中";
          break;
        case 2:
          _text = "通过";
          break;
        default:
          _text = "驳回";
      }
      return _text;
    },
    // 列表新增
    addMission(val) {
      this.$router.push({
        path: "/RecordList",
        query: {
          type: "1",
          parentId: val.id,
          departmentName: val.departmentName
        }
      });
    },
    addnewTask() {
      let _this = this.form;
      if (_this.name == "" || _this.departmentId == "" || _this.title == "") {
        this.$message({
          message: "输入框不能为空",
          type: "warning"
        });
        return;
      }

      if (!Array.isArray(_this.departmentId)) {
        _this.departmentId = [_this.departmentId];
      }
      _this.departmentId = _this.departmentId[_this.departmentId.length - 1];
      if (this.up) {
        this.$axios
          .post("/task/update", this.form, 2)
          .then(res => {
            if (res.code == 200) {
              for (const key in this.form) {
                this.form[key] = "";
              }
              this.$message({
                message: "数据更新成功",
                type: "success"
              });
              this.dialogFormVisible = false;
              this.getListByPage();
            }
          })
          .catch(err => {
            console.log(err);
          });
        return;
      }
      this.$axios
        .post("/task/add", this.form, 2)
        .then(res => {
          if (res.code == 200) {
            for (const key in this.form) {
              this.form[key] = "";
            }
            this.$message({
              message: "数据更新成功",
              type: "success"
            });
            this.dialogFormVisible = false;
            this.getListByPage();
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 获取部门信息列表
    getbranchList() {
      this.$axios
        .post("/dept/getList")
        .then(res => {
          if (res.code == 200) {
            this.branchList = res.data;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    addTask() {
      this.up = false;
      this.isFlag = true;
      let _this = this.form;
      for (const key in _this) {
        _this[key] = "";
      }
      this.form.year = "2020";
      this.form.departmentId = "";
      this.dialogFormVisible = true;
    },
    updata(val) {
      this.up = true;
      this.isFlag = false;
      console.log(val);
      let _this = this.form;
      let _id = val.id;
      let _obj = {
        id: _id
      };

      this.$axios
        .post("/task/load", _obj, 2)
        .then(res => {
          if (res.code == 200) {
            let _val = res.data;
            if (_val.parentId) {
              this.value1 = true;
              _this.name = _val.name;
              _this.title = _val.title;
              _this.parentId = _val.parentId;
            } else {
              this.value1 = false;
              _this.name = _val.name;
              _this.title = _val.title;
              _this.parentId = "";
            }
            _this.year = _val.year + "";
            _this.departmentId = _val.departmentId;
            _this.id = _val.id;
            this.dialogFormVisible = true;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    dataTotal(val) {
      this.pageNum = val;
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (rowIndex % 2 === 0) {
        if (columnIndex === 0) {
          return [1, 2];
        } else if (columnIndex === 1) {
          return [0, 0];
        }
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        const _row = this.spanData[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },
    handleAmend(val) {
      this.$router.push({
        path: "/RecordList",
        query: {
          id: val.id
        }
      });
    },
    // 删除
    handleDelete(val) {
      let _obj = {
        id: val.id
      };
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios
            .post("/task/remove", _obj, 2)
            .then(res => {
              if (res.code == 200) {
                this.getListByPage();
                this.$message({
                  message: "数据更新成功",
                  type: "success"
                });
              }
            })
            .catch(err => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 获取数据列表
    getListByPage() {
      this.$axios
        .post(`/task/getList`)
        .then(res => {
          if (res.code == 200) {
            this.tableData = res.data;
            let _taskId = localStorage.getItem("taskId");
            console.log(_taskId);
            this.tableData.forEach((item, index) => {
              if (_taskId == "null" || _taskId == "undefined") {
                item.isDisplay = true;
                if (item.children || scope.row.children.length != 0) {
                  item.children.forEach((i, index2) => {
                    i.isDisplay = true;
                    i.index = `${index + 1}.${index2 + 1}`;
                  });
                }
                item.index = index + 1;
              } else {
                item.index = index + 1;
                if (item.id == _taskId) {
                  item.isDisplay = true;
                } else {
                  item.isDisplay = false;
                }
              }
            });
            this.tableDataboy = [];
            this.tableDataboy = this.tableData.filter(function(
              element,
              index,
              self
            ) {
              return self.findIndex(el => el.id == element.id) === index;
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    getSpanData(data) {
      // 存放计算好的合并单元格的规则
      this.spanData = [];
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanData.push(1);
          this.pos = 0;
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].id === data[i - 1].id) {
            this.spanData[this.pos] += 1;
            this.spanData.push(0);
          } else {
            this.spanData.push(1);
            this.pos = i;
          }
        }
      }
    },
    // 表格数组
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 查看按钮
    routerPath(val) {
      console.log(val);
      this.$router.push({
        path: "/taskScore",
        query: {
          taskId: val.id,
          departmentName: val.departmentName,
          number: val.number,
          checkStatus: val.checkStatus,
          name: val.name
        }
      });
    },
    // 申请审核
    audit(val) {
      console.log(val);

      this.$axios
        .post(
          `/task/auditing`,
          {
            id: val.id
          },
          2
        )
        .then(res => {
          if (res.code == 200) {
            this.$message({
              message: "已成功提交审核！",
              type: "success"
            });
            this.getListByPage();
          } else {
            this.$message.error(`${res.msg}`);
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
  }
};
</script>
<style scoped>
.page {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.header {
  float: left;
  width: 100%;
  height: 52px;
  text-align: left;
  background: rgb(252, 248, 248);
}
.main {
  width: 100%;
  height: 100%;
}
.subnav {
  float: left;
  width: 100%;
  height: 60px;
  line-height: 60px;
  padding: 0 20%;
}
.searchLeft {
  float: left;
  width: 400px;
  /* height: 40px; */
}
.searchLeft > button {
  width: 100px;
  height: 40px;
  background: #409eff;
  color: #fff;
  border: 0px;
  font-size: 16px;
  text-align: center;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
  position: relative;
  left: -8px;
  top: 1px;
}
.searchRight {
  float: left;
  width: auto;
}
.searchRight > span {
  display: inline-block;
  width: 80px;
  height: auto;
  font-size: 14px;
  text-align: center;
  margin-left: 20px;
}
.el-scrollbar__wrap {
  overflow-x: hidden;
}
.page-component__scroll {
  height: 100%;
}
.list {
  width: 100%;
  height: 100%;
  padding-bottom: 60px;
}
.laypage {
  width: 100%;
  height: 60px;
  position: relative;
  top: -60px;
  text-align: right;
}
.radio {
  width: 100%;
  height: 40px;
  line-height: 40px;
  text-align: right;
}
</style>
<style>
#indicatorsList .el-scrollbar__wrap {
  overflow: visible;
  overflow-y: scroll;
}
</style>
